<?php
/**
 * Created by PhpStorm.
 * User: chl
 * Date: 2017/3/23 0023
 * Time: 17:45
 */
namespace app\admin\controller;
use app\models\Bases;
use think\Db;
class Order extends Base{
    public function orderList(){
        $get = input('param.');
        $search = search($get,'a.create_time','a.order_no,c.username,c.real_name');
        $where  = $search['condition'];
        if(!empty($get['status'])){
            $where .= " and a.status = ".$get['status'];
            $search['display']['status'] = $get['status'];
        }
        if(!empty($get['product_id'])){
            $where .= " and a.product_id = ".$get['product_id'];
            $search['display']['product_id'] = $get['product_id'];
        }
        if(!empty($get['payStartTime']) && empty($get['payEndTime']) ){
            $starttime = strtotime($get['payStartTime']);
            $where .= " and pay_time >= ".$starttime;
            $search['display']['payStartTime'] = $get['payStartTime'];
        }
        if(!empty($get['payEndTime']) && empty($get['payStartTime']) ){
            $endtime = strtotime($get['payEndTime'])+3600*24;
            $where .= " and pay_time <= ".$endtime;
            $search['display']['payEndTime'] = $get['payEndTime'];

        }
        if(!empty($get['payStartTime']) && !empty($get['payEndTime'])){
            $starttime = strtotime($get['payStartTime']);
            $endtime = strtotime($get['payEndTime']) +3600*24;
            $where .= " and pay_time >= ".$starttime." and pay_time <= ".$endtime;
            $search['display']['payStartTime'] = $get['payStartTime'];
            $search['display']['payEndTime'] = $get['payEndTime'];
        }
        $field  = "a.*,b.name,duration,c.username,real_name";
        $join   = [['product b','a.product_id = b.product_id','LEFT'],['user c','a.uid = c.uid','LEFT']];
        $result['list']= Db::name('order')->alias('a')->join($join)->where($where)->field($field)->order('a.order_id desc')->paginate(15,false,[
            'query' => $get,
        ]);
        $productModel = new Bases('product');
        $productInfo  = $productModel->selectData();
        return view('orderList',['result'=>$result,'display'=>$search['display'],'productInfo'=>$productInfo]);
    }

    public function orderAdd(){
        $uid = intval(input('uid'));
        $userModel = new Bases('user');
        $productModel = new Bases('product');
        $orderModel  = new Bases('order');
        $productInfo  = $productModel->selectData();
        $userInfo  = $userModel->find('uid = '.$uid);
        if(request()->isPost()){
            $post = input('param.');
            if(empty($post['real_name'])){
                return self::formatResult(405,'客户姓名不能为空');
            }
            $userModel->setField(" uid =".$post['uid'],['real_name'=>trim($post['real_name'])]);//修改真实姓名
            $orderOne = $orderModel->find('uid ='.$post['uid'].' and status = 2');
            $productOne = $productModel->find('product_id = '.$post['product_id']);
            if(!empty($orderOne)){
                //查詢上一條訂單信息
                if($orderOne['expiration_time'] >= time()){
                    //還沒過期
                    $addOrder['effective_time']  = $orderOne['expiration_time'];//生效時間為上賬訂單的過期時間
                    $addOrder['expiration_time'] = $orderOne['expiration_time'] + $productOne['duration'];//過期時間 = 上個定單的過期時間 + 產品的時長
                }else{
                    //過期了
                    $addOrder['expiration_time'] = strtotime(date('Y-m-d'.'00:00:00',time())) + 24*3600 + $productOne['duration'];// 過期時間 = 今天的時間戳開始時間 +一天+產品時長
                    $addOrder['effective_time'] = time();
                }
                $addOrder['money'] = $productOne['market_price'];//市場價
            }else{//之前沒有訂單
                $addOrder['expiration_time'] = strtotime(date('Y-m-d'.'00:00:00',time())) + 24*3600*2-1 + $productOne['duration'];// 過期時間 = 今天的時間戳開始時間 +一天+產品時長

                $addOrder['effective_time'] = time();
                $addOrder['money'] = $productOne['discounted_price'];//優惠價
            }
            $addOrder['status'] = 2;
            $addOrder['pay_time'] = time();
            $addOrder['create_time'] = time();
            $addOrder['order_no'] = date('YmdHis',time()).rand(100000,999999);//訂單編號
            $addOrder['product_id'] = $post['product_id'];
            $addOrder['uid'] = $post['uid'];
            $addOrder['type'] = 3;//線下支付
            $rs = $orderModel->insertData($addOrder);
            if($rs){
                $order_id = $userModel->find('uid ='.$post['uid'],'order_id');//查詢用戶存儲的訂單
                //dump($order_id);exit;
                if(!empty($order_id['order_id'])){
                    $order = $orderModel->find('order_id ='.$order_id['order_id']);
                    if(!empty($order) && $order['expiration_time'] <= time()){//有訂單信息並且過期了
                        $data['order_id'] = $rs;
                        $data['uid'] = $post['uid'];
                        $userModel->updateData($data);//跟新訂單
                    }
                    return self::formatSuccessResult();
                }else{
                    $data['order_id'] = $rs;
                    $data['uid'] = $post['uid'];
                    $userModel->updateData($data);//跟新訂單
                    return self::formatSuccessResult();
                }
            }return self::formatResult(406,'操作失敗');
        }
        return view('orderAdd',['result'=>$userInfo,'productInfo'=>$productInfo]);
    }
    //订单计划任务，用户判断用户当前订单是否过期，过期则使用下一个有效订单（若果没有有限订单则不修改只显示会员到期）
    public function orderPlayTesk(){
        $userModel = new Bases('user');
        $orderModel= new Bases('order');
        $orderPlayTesk = new Bases('order_play_tesk');
        try{
            $userWhere = " type =3 and order_id != 0 ";
            $userInfo = $userModel->selectData($userWhere);//获取已开通订单用户的所有信息
            if(empty($userInfo)){
                return ;
            }

            foreach($userInfo as $v){
                $uid = $v['uid'];//用户uid
                $order_id = $v['order_id'];//用户现在的订单id
                $orderOne = $orderModel->find('order_id = '.$order_id);//找到改订单并作是否过期判断
                if(empty($orderOne)){
                    return ;
                }
                if($orderOne['expiration_time'] >= time()){
                    //没有过期，不做任何操作
                    return ;
                }
                $orderInfo = $orderModel->selectData('uid = '.$uid,'','expiration_time asc');//按照过期时间升序排列
                if(empty($orderInfo)){
                    throw new \LogicException('没有改用户的订单',10002);
                }
                foreach($orderInfo as $v1){
                    if($v1['expiration_time'] > time() ){
                        $rs = $userModel->updateData(['order_id'=>$v1['order_id']],['uid'=>$v1['uid']]);//找到没有过期的订单，跟新用户的订单order_id，并结束循环
                        if($rs !== false){
                            $orderPlayTesk->insertData(['uid'=>$v1['uid'],'order_id'=>$v1['order_id'],'create_time'=>time()]);
                        }
                        continue;
                    }
                }

            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }

    }
}